"""
Support module for logAnalyzer.py to store the packet information.

Saves the blocked packet information for later analysis.
"""

from support import geoip

class packet:
	"""Stores the blocked packet information"""
	def __init__(self):
		self.timestamp = ''
		self.MACIN = ''
		self.MACOUT = ''
		self.direction = ''
		self.IP = ''
		self.country = ''
		self.city = ''
		self.longitude = ''
		self.latitude = ''
		
	def __str__(self):
		"""Default String Output"""
		return "Packet: " + str(self.timestamp) + " - " + str(self.country)
		
	def createFromUFW(self,logLine):
		"""Processes a packet from a UFW type log"""
		lineValues = logLine.split(' ',4)
		self.timestamp = lineValues[0:3]
		packetDetails = lineValues[4].split('[UFW BLOCK] ')[1].split(' ')
		for x in packetDetails:
			self.processAtributes(x)
	
	def createFromIptables(self,logLine):
		"""Processes a packet from a ipTables/netlog default type log"""
		lineValues = logLine.split(' ',4)
		self.timestamp = lineValues[0:3]
		
		packetDetails = lineValues[4].split('kernel: ')[1].split(' ',1)[1].split(' ')
		for x in packetDetails:
			self.processAtributes(x)
			
	def processAtributes(self,atrib):
		"""processes each packet atribute and stores it in the packet object"""
		if 'IN=' in atrib:
			if len(atrib) > 3:
				self.direction = 'IN'
			else:
				self.direction = 'OUT'
		elif 'MAC=' in atrib:
			if (self.direction == 'IN'):
				self.MACIN = atrib[22:39]
				self.MACOUT = atrib[4:21]
			else:
				self.MACIN = atrib[4:21]
				self.MACOUT = atrib[22:39]				
		elif 'SRC=' in atrib:
			if (self.direction == 'IN'):
				self.IP = atrib.split('=')[1]
		elif 'DST=' in atrib:
			if (self.direction == 'OUT'):
				self.IP = atrib.split('=')[1]
		
	def getLocations(self):
		"""Gets object ip's location(country and city)"""
		local = geoip.getLocation(self.IP)
		self.country = local.getCountry()
		if self.country == '':
			self.country = 'Unknown'
		c = local.getCity()
		self.city = c['city']
		if self.city == '' or self.city == 'unknown':
			self.city = 'Unknown'
		self.longitude = c['log']
		self.latitude = c['lat']
		
	
